package dao

import (
	"gorm.io/gorm"
	"morleyStoneHome/model"
)

type stoRewardDao struct {
}

var StoRewardDao = newStoRewardDao()

func newStoRewardDao() *stoRewardDao {
	return &stoRewardDao{}
}

//增单条
func (n *stoRewardDao) Insert(stoReward *model.StoReward) error {
	err := Db.Create(stoReward).Error
	if nil != err {
		return err
	}
	return nil
}

//更新单条
func (n *stoRewardDao) Update(uid int, stoReward *model.StoReward) error {
	err := Db.Model(&model.StoReward{}).Where("uid = ? ", uid).Updates(stoReward).Error
	if nil != err {
		return err
	}
	return nil
}

//更新单条
func (n *stoRewardDao) UpdateByMap(uid int, m map[string]interface{}) error {
	err := Db.Model(&model.StoReward{}).Where("uid = ? ", uid).Updates(m).Error
	if nil != err {
		return err
	}
	return nil
}

//余生减一
func (n *stoRewardDao) UpdateLife() error {
	err := Db.Model(&model.StoReward{}).Where("stake_life > ?", 0).UpdateColumn("stake_life", gorm.Expr("stake_life - ?", 1)).Error
	if nil != err {
		return err
	}
	return nil
}

//查单条
func (n *stoRewardDao) FindOne(uid int) (stoReward []model.StoReward, err error) {
	res := Db.Where("uid = ? ", uid).Find(&stoReward)
	if res.Error != nil {
		return nil, res.Error
	}
	return stoReward, nil
}

//查单条
func (n *stoRewardDao) FindOneByAddr(addr string) (stoReward []model.StoReward, err error) {
	res := Db.Where("addr = ? ", addr).Find(&stoReward)
	if res.Error != nil {
		return nil, res.Error
	}
	return stoReward, nil
}

//查存活的单条
func (n *stoRewardDao) FindOneAlive(uid int) (stoReward []model.StoReward, err error) {
	res := Db.Where("uid = ? and stake_life > 0 ", uid).Find(&stoReward)
	if res.Error != nil {
		return nil, res.Error
	}
	return stoReward, nil
}
